const Base = require('./base.js');
const crypto = require('crypto');

module.exports = class extends Base {
  async loginAction() {
    const username = this.post('username');
    const password = this.post('password');

    const admin = await this.model('admin_list')
      .where({ username: username })
      .find();

    if (think.isEmpty(admin)) {
      return this.fail(401, '用户名或密码不正确');
    }
    if (admin.status === 1) {
      return this.fail(401, '用户被停用');
    }

    const hash = crypto.createHash('md5');
    hash.update(password);
    const md5 = hash.digest('hex');
    if (admin.password !== md5) {
      return this.fail(400, '用户名或密码不正确');
    }

    // 更新登录信息
    await this.model('admin_list')
      .where({ id: admin.id })
      .update({
        gmt_last_login: ['exp', 'CURRENT_TIMESTAMP()'],
      });

    const TokenSerivce = this.service('token', 'admin');
    const sessionKey = await TokenSerivce.create({
      user_id: admin.id,
      area_id: admin.area_id,
    });

    if (think.isEmpty(sessionKey)) {
      return this.fail('登录失败');
    }

    const userInfo = {
      user_id: admin.id,
      access_token: sessionKey,
      username: admin.username,
    };

    return this.success(userInfo);
  }
  async infoAction() {
    const admin = await this.model('admin_list')
      .where({ id: this.getLoginUserId() })
      .field('name, role_type, id')
      .find();
    // let permissions = [];
    // if (admin.role_type > 6) {
    //   permissions = admin.role_type;
    // }
    return this.success({
      permissions: admin.role_type,
      roles: [1],
      sysUser: admin,
    });
  }

  async changeAction() {
    const values = this.post();
    const admin = await this.model('admin_list')
      .where({ id: this.getLoginUserId() })
      .find();

    const hash = crypto.createHash('md5');
    hash.update(values.password);
    const md5 = hash.digest('hex');
    if (admin.password !== md5) {
      return this.fail(400, '原密码不正确');
    }

    if (values.newpassword1 !== values.newpassword2) {
      return this.fail(400, '两次密码输入不一致');
    }

    const hashNew = crypto.createHash('md5');
    hashNew.update(values.newpassword1);
    const md5New = hashNew.digest('hex');

    await this.model('admin_list')
      .where({ id: this.getLoginUserId() })
      .update({
        password: md5New,
      });

    return this.success();
  }

  async logoutAction() {
    return this.success();
  }
};
